/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.transas.zornav.file;

import com.transas.zornav.data.DataSource;
import java.io.IOException;
import java.io.Reader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 *
 * @author amalikov
 */
public class KmlDataSourceReader implements DataSourceReader {
	private final static Logger LOG = Logger.getLogger(KmlDataSourceReader.class.getName());

	@Override
	public void process(Reader file, DataSource ds) {
		try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Element root = db.parse(new InputSource(file)).getDocumentElement();
			Element document = (Element)root.getElementsByTagName("Document").item(0);
			Element placemark = (Element)document.getElementsByTagName("Placemark").item(0);
			Element linestring = (Element)placemark.getElementsByTagName("LineString").item(0);
			Element coordinates = (Element)linestring.getElementsByTagName("coordinates").item(0);
			String coordinatesValue = coordinates.getTextContent();
			
			String[] coords = coordinatesValue.split(" ");
			int i = ds.getSize();
			for (String coord : coords) {
				String[] values = coord.split(",");
				if (values.length == 3) {
					ds.addRow();
					ds.setValue(ds.getHandle("N"), i, i);
					ds.setValue(ds.getHandle("Latitude"), i, Double.parseDouble(values[1]));
					ds.setValue(ds.getHandle("Longitude"), i, Double.parseDouble(values[0]));
					ds.setValue(ds.getHandle("Altitude"), i, Double.parseDouble(values[2]));
					++i;
				}
			}
		} catch (SAXException ex) {
            LOG.log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
	}
}
